/* thread.c
 * 
 *  POSIX thread API wrapper
 */
#include <pthread.h>

#include <librally.h>

Err rp_thread_run(rp_cond_t *cond);			// TODO: need to DONE

Err rp_thread_create(rp_thread_t *tid, ThreadFunc func, void *arg)
{
	static char fname[] = "rp_thread_create";
	static char msg[] = "fatal error";
	Err err;
	pthread_attr_t attr;
	FLOG_IN(fname);

	pthread_attr_init(&attr);
	pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);		// bind state
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

	if (pthread_create(tid, &attr, func, arg))
	{
		rp_log(LOG_CRITICAL, fname, "Failed to create new thread. Error: %s", strerror(errno));
		return E_ERROR;
	}

	FLOG_OUT(fname);
	return E_OK;
}

Err rp_thread_cancel(rp_thread_t tid)
{
	static char fname[] = "rp_thread_create";
	static char msg[] = "fatal error";
	Err err;
	FLOG_IN(fname);

	if (!pthread_cancel(tid))
	{
		rp_log(LOG_CRITICAL, fname, "Failed to cancel thread. Error: %s", strerror(errno));
	}	

	FLOG_OUT(fname);
	return err;
}

void rp_thread_exit()
{
	static char fname[] = "rp_thread_exit";
	static char msg[] = "fatal error";
	Err err;
	FLOG_IN(fname);

	pthread_exit(NULL);
	rp_log(LOG_CRITICAL, fname, "Thread failed to exit. Error: %s", strerror(errno));

	FLOG_OUT(fname);
	return;
}

rp_thread_t rp_thread_self()
{
	static char fname[] = "rp_thread_exit";
	static char msg[] = "fatal error";
	Err err;
	rp_thread_t tid;
	FLOG_IN(fname);
	
	tid = pthread_self();

	FLOG_OUT(fname);
	return tid;
}

